package com.ursu.server.handler;

import java.util.logging.Logger;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.gwtplatform.dispatch.server.actionhandler.ActionHandler;
import com.ursu.server.dao.UserDao;
import com.ursu.shared.User;
import com.ursu.shared.actions.CreateUser;
import com.ursu.shared.actions.CreateUserResult;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.gwtplatform.dispatch.server.ExecutionContext;
import com.gwtplatform.dispatch.shared.ActionException;

public class CreateUserActionHandler implements
		ActionHandler<CreateUser, CreateUserResult> {
	
	private final Provider<HttpServletRequest> requestProvider;
	private static final Logger log = Logger.getLogger("CreateUserActionHandler");

	@Inject
	public CreateUserActionHandler(final ServletContext servletContext,
		      final Provider<HttpServletRequest> requestProvider) {
		this.requestProvider = requestProvider;
	}

	@Override
	public CreateUserResult execute(CreateUser action, ExecutionContext context)
			throws ActionException {
		//This should reeeeaaaaaly be cleaned out
		UserDao dao = new UserDao();
		
		log.severe("\nReceived user:"+
					"\n Username: "+ action.getUserToCreate().getUsername()+
					"\n Recieved password: "+ action.getUserToCreate().getHashedPassword()+
					"\n Email: " +action.getUserToCreate().getEmail());
		String sessionId = null;
		String dataStoreId = null;
		User userToCreate = action.getUserToCreate();
		
		if(userToCreate == null )
		{
			log.severe("\nreturned because userToCreate was null!!!");
			return new CreateUserResult(sessionId, dataStoreId);
		}
		else {
			dataStoreId =  dao.createUser(userToCreate);
			log.severe("\n From dao.CreateUser(), the datastoreId is: " +dataStoreId);
			if (dataStoreId != null) {
				HttpSession session = requestProvider.get().getSession();
				session.setAttribute("login.authenticated", userToCreate.getUsername());
				sessionId = session.getId();
				return new CreateUserResult(sessionId, dataStoreId);
			}
			else return new CreateUserResult(sessionId, dataStoreId) ;
		}
		
	}

	@Override
	public void undo(CreateUser action, CreateUserResult result,
			ExecutionContext context) throws ActionException {
	}

	@Override
	public Class<CreateUser> getActionType() {
		return CreateUser.class;
	}
}
